package com.work.keep.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.work.keep.R;
import com.work.keep.adapter.DynamicDetailsRecyclerAdapter;
import com.work.keep.base.BaseActivity;
import com.work.keep.datas.DynamicDetailsData;
import com.work.keep.entity.dao.Collection;
import com.work.keep.entity.dao.CollectionComments;
import com.work.keep.entity.dao.CollectionCommentsDao;
import com.work.keep.entity.dao.CollectionDao;
import com.work.keep.entity.dao.DaoSingleton;
import com.work.keep.ui.PullToRefreshRecyclerView;
import com.work.keep.volley.VolleySingleton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态详情 页面 listView Item detail_comments_item https://api.gotokeep.com/v1.1/entries/569cdd8b8c3e7eac2f42449c/comments?lastId=569ce32d1b7f894517f174b9&limit=20&reverse=true
 * Created by dllo on 16/1/19.
 * 未注册//
 */
public class DynamicDetailsActivity extends BaseActivity {
    private NetworkImageView dynamicDetailsAvater, dynamicDetailsNI, dynamicDetailsAvater0, dynamicDetailsAvater1, dynamicDetailsAvater2, dynamicDetailsAvater3;
    private TextView dynamicDetailsName, dynamicDetailsDate, dynamicDetailsContent, dynamicDetailsLikesCount, dynamicDetailsCommentCounts;
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;
    private boolean mIsStart = true;
    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
    private static String _id = "569ce32d1b7f894517f174b9";
    private ImageView dynamicDetailsCollection, dynamicDetailsLikes, dynamicDetailsComment;
    private boolean flagsCollection = false;
    private boolean flagsLikes = false;
    private boolean flagsComments = false;
    private PullToRefreshRecyclerView pullToRefreshRecycler;
    private RecyclerView recyclerView;
    private DynamicDetailsRecyclerAdapter recyclerAdapter;
    //需要存入数据库的 boolean
    private boolean flags = false;
    private CollectionDao collectionDao;
    private CollectionCommentsDao collectionCommentsDao;
    //数据库两条信息
    private Collection collection;
    List<CollectionComments> collectionComments;

    public static void goToDynamicDetailActivity(Context context, String _id) {
        Intent intent = new Intent(context, DynamicDetailsActivity.class);
        DynamicDetailsActivity._id = _id;
        Log.d("fff", _id);
        context.startActivity(intent);
    }

    @Override
    protected View getLayoutView() {
        return null;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_details_coor;
    }

    @Override
    protected void initView() {
        recyclerView = (RecyclerView) findViewById(R.id.activityDetailsRecycler);
        dynamicDetailsNI = (NetworkImageView) findViewById(R.id.dynamicDetailsNI);
        dynamicDetailsContent = (TextView) findViewById(R.id.dynamicDetailsContent);
        dynamicDetailsDate = (TextView) findViewById(R.id.dynamicDetailsDate);
        dynamicDetailsName = (TextView) findViewById(R.id.dynamicDetailsName);
        dynamicDetailsAvater = (NetworkImageView) findViewById(R.id.dynamicDetailsAvater);
        dynamicDetailsCollection = (ImageView) findViewById(R.id.dynamicDetailsCollection);
    }

    @Override
    protected void initData() {
        volleySingleton = VolleySingleton.getInstance();
        imageLoader = volleySingleton._getImageLoader();
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        collectionCommentsDao = DaoSingleton.getInstance().getCollectionCommentsDao();
        recyclerAdapter = new DynamicDetailsRecyclerAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(recyclerAdapter);


        ;
//        pullToRefreshRecycler.setPullLoadEnabled(true);
//        pullToRefreshRecycler.setScrollLoadEnabled(false);


//        dynamicDetailsCollection.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (flagsCollection) {
//                    flagsCollection = false;
//                    dynamicDetailsCollection.setImageResource(R.mipmap.collection);
//                } else {
//                    flagsCollection = true;
//                    dynamicDetailsCollection.setImageResource(R.mipmap.collection_on);
//                }
//
//            }
//        });


//        GsonRequest<>
        initRecyclerView();


    }

    //加载点赞人的头像
    private void initLikerAvater() {
        List<NetworkImageView> avaters = new ArrayList<>();
        avaters.add(dynamicDetailsAvater0);
        avaters.add(dynamicDetailsAvater1);
        avaters.add(dynamicDetailsAvater2);
        avaters.add(dynamicDetailsAvater3);
        for (int i = 0; i < avaters.size(); i++) {
            avaters.get(i).setDefaultImageResId(R.mipmap.person_45_45);
            avaters.get(i).setErrorImageResId(R.mipmap.person_45_45);
//            avaters.get(i).setImageUrl();

        }
    }

    //加载动态发布的自拍
    private void initPhoto(DynamicDetailsData datas) {
        dynamicDetailsNI.setDefaultImageResId(R.mipmap.person_45_45);
        dynamicDetailsNI.setErrorImageResId(R.mipmap.person_45_45);
        dynamicDetailsNI.setImageUrl(datas.getData().getPhoto(), imageLoader);
    }

    //加载用户头像


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }


    //装载数据库数据的方法
    private void loadDBData(DynamicDetailsData responseDatas) {
        collection = new Collection();
        collection.setKey(responseDatas.getData().getId());
        collection.setAvater(responseDatas.getData().getAuthor().getAvatar());
        collection.setContent(responseDatas.getData().getContent());
        collection.setCreated(responseDatas.getData().getCreated());
        collection.setPhoto(responseDatas.getData().getPhoto());
        collection.setUsername(responseDatas.getData().getAuthor().getUsername());
        collectionComments = new ArrayList<CollectionComments>();
        for (int i = 0; i < responseDatas.getData().getCommentsList().size(); i++) {
            DynamicDetailsData.DataEntity.CommentsListEntity entity = responseDatas.getData().getCommentsList().get(i);
            CollectionComments comment = new CollectionComments();
            comment.setUsername(entity.getAuthor().getUsername());
            comment.setKey(responseDatas.getData().getId());
            comment.setCotent(entity.getContent());
            collectionComments.add(comment);
        }
    }

    //加载listView的数据
    private void initRecyclerView() {
        String url = "https://api.gotokeep.com/v1.1/entries/" + _id + "?limit=20&reverse=true";
        flags = collectionDao.queryBuilder().where(CollectionDao.Properties.Key.eq(_id)).list().size() > 0;
        StringRequest detailsStringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                final DynamicDetailsData datas = JSON.parseObject(response, DynamicDetailsData.class);
                recyclerAdapter.addData(datas.getData().getCommentsList());
                addData(datas);
                initPhoto(datas);
                final String author_id = datas.getData().getAuthor().getId();
                //升级一次
                if (flags) {
                    loadDBData(datas);
                    dynamicDetailsCollection.setImageResource(R.mipmap.collection_on);
                }
                dynamicDetailsCollection.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (flags) {
                            flags = false;
                            dynamicDetailsCollection.setImageResource(R.mipmap.collection);
                            collectionDao.delete(collection);
                            collectionCommentsDao.deleteInTx(collectionComments);
                        } else {
                            loadDBData(datas);
                            flags = true;
                            dynamicDetailsCollection.setImageResource(R.mipmap.collection_on);
                            collectionDao.insert(collection);
                            collectionCommentsDao.insertInTx(collectionComments);
                        }
                    }
                });


                dynamicDetailsName.setText(datas.getData().getAuthor().getUsername());
                dynamicDetailsDate.setText(datas.getData().getCreated().substring(0, 10));
                dynamicDetailsContent.setText(datas.getData().getContent());
                dynamicDetailsAvater.setDefaultImageResId(R.mipmap.person_45_45);
                dynamicDetailsAvater.setErrorImageResId(R.mipmap.person_45_45);
                dynamicDetailsAvater.setImageUrl(datas.getData().getAuthor().getAvatar(), imageLoader);
                dynamicDetailsAvater.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(DynamicDetailsActivity.this, PeopleActivity.class);
                        intent.putExtra("_id", author_id);
                        startActivity(intent);
                    }
                });
                dynamicDetailsName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(DynamicDetailsActivity.this, PeopleActivity.class);
                        intent.putExtra("_id", author_id);
                        startActivity(intent);
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //网络请求失败进入此
                if (flags) {
                    dynamicDetailsCollection.setImageResource(R.mipmap.collection_on);
                    Toast.makeText(DynamicDetailsActivity.this, "onc", Toast.LENGTH_SHORT).show();
                    collection = collectionDao.queryBuilder().where(CollectionDao.Properties.Key.eq(_id)).list().get(0);
                    dynamicDetailsName.setText(collection.getUsername());
                    dynamicDetailsAvater.setImageUrl(collection.getAvater(), imageLoader);
                    dynamicDetailsContent.setText(collection.getContent());
                    dynamicDetailsDate.setText(collection.getCreated().substring(0, 10));
                    dynamicDetailsNI.setImageUrl(collection.getPhoto(), imageLoader);
                    if (collectionCommentsDao.queryBuilder().where(CollectionCommentsDao.Properties.Key.eq(_id)).list().size() > 0) {
                        recyclerAdapter.addDBData(collectionCommentsDao.queryBuilder().where(CollectionCommentsDao.Properties.Key.eq(_id)).list());
                    }
                }
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> detailsHeader = new HashMap<>();
                detailsHeader.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjY1MDBlMTYzZGIwYzlmNTdiMTQwYWQiLCJ1c2VybmFtZSI6Iuaeq-WQmyIsImF2YXRhciI6Imh0dHA6Ly93eC5xbG9nby5jbi9tbW9wZW4vc2t3MmhSR3lXRWcwUzV0NzhkMlRVUnFhYjBzcWJ4RXB4S1BLUFpEOXpwbTNJbkIySzRjRnhLVEJsemdDb3VIcGlia3RkRUluQ0NFcGpIS2FHZ1lwRkp6SVRIVU5NYTNpYmYvMCIsImlhdCI6MTQ1MzQ0NDgyNywiZXhwIjoxNDU2MDM2ODI3LCJpc3MiOiJodHRwOi8vd3d3LmdvdG9rZWVwLmNvbS8ifQ.qcYVm3A8SPdiMkjVpp_ZwjLKw0Skws4m2yozvOctsQM");
                detailsHeader.put("X-X", "82241e05792e6420a945b049783997f95de556f4");
                detailsHeader.put("Host", "api.gotokeep.com");
                return detailsHeader;
            }
        };

        volleySingleton._addRequest(detailsStringRequest);
    }

    private void addData(DynamicDetailsData datas) {

    }

    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            //回来可以在这里做判断
            boolean hasMoreData = true;
            if (mIsStart) {
//                demoAdapter.refresh();
            } else {
//                demoAdapter.loadMore();
            }
            pullToRefreshRecycler.onPullDownRefreshComplete();
            pullToRefreshRecycler.onPullUpRefreshComplete();
            pullToRefreshRecycler.setHasMoreData(hasMoreData);
            String text = formatDateTime(System.currentTimeMillis());
            pullToRefreshRecycler.setLastUpdatedLabel(text);
            super.onPostExecute(aVoid);

        }
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }
}
